package com.kayo.specimen.utility;


import java.security.InvalidParameterException;
import java.util.StringJoiner;

public class OrderByBuilder {
    private StringJoiner result = new StringJoiner(",");

    public OrderByBuilder() {
    }

    public OrderByBuilder(String text) {
        if (text.isEmpty())
            return;

        String[] para = text.split("|");
        if (para.length != 2)
            throw new InvalidParameterException("排序文本参数不正确。");

        String[] sorts = para[0].split(",");
        String[] orders = para[1].split(",");
        if (sorts.length != orders.length)
            throw new InvalidParameterException("sort字段必须和order排序数量一致。");

        for (int i = 0; i < sorts.length; i++) {
            this.result.add(String.format("%s %s", sorts[i], orders[i]));
        }
    }

    public OrderByBuilder(String field, boolean isDescend) {
        this.result.add(String.format("%s %s", field, isDescend ? "desc" : "asc"));
    }

    public OrderByBuilder(String sort, String order) {
        if (sort.indexOf(",") > 0 && order.indexOf(",") > 0) {
            String[] sorts = sort.split(",");
            String[] orders = order.split(",");
            if (sorts.length != orders.length)
                throw new InvalidParameterException("sort字段必须和order排序数量一致。");

            for (int i = 0; i < sorts.length; i++) {
                this.result.add(String.format("%s %s", sorts[i], orders[i]));
            }
        }
        else
            this.result.add(String.format("%s %s",sort,order));

    }

    public OrderByBuilder addOrder(String field, boolean isDescend) {
        this.result.add(String.format("%s %s", field, isDescend ? "desc" : "asc"));
        return this;
    }

    @Override
    public String toString() {
        return result.toString();
    }
}
